package com.lanyou.esb.redis.proxy.base;

import java.io.IOException;
import java.lang.reflect.ParameterizedType;

import redis.clients.jedis.Jedis;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.lanyou.esb.common.Constants4Redis;
import com.lanyou.esb.redis.proxy.JedisProxy;

/**
 * 操作Redis基础代理类
 * 
 * @author Davey.wu
 */
public abstract class BaseJedisProxy<T> implements JedisProxy<T> {
	private Class<T> classes;

	public Class<T> getClasses() {
		return classes;
	}

	/** 键分隔符 **/
	public static final String KEY_SEPARATOR = Constants4Redis.KEY_SEPARATOR;

	public BaseJedisProxy() {
		ParameterizedType pt = (ParameterizedType) this.getClass()
				.getGenericSuperclass();
		classes = (Class<T>) pt.getActualTypeArguments()[0];
	}

	@Override
	public T erase(Jedis jedis) throws JsonParseException,
			JsonMappingException, IOException {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public void unErase(Jedis jedis, T target) throws JsonParseException,
			JsonMappingException, IOException {
		// TODO Auto-generated method stub
	}

	/**
	 * 将JSON字符串转成对象
	 * 
	 * @param value
	 * @return
	 * @throws IOException
	 * @throws JsonMappingException
	 * @throws JsonParseException
	 */
	public T fromJson(String value) throws JsonParseException,
			JsonMappingException, IOException {
		ObjectMapper mapper = new ObjectMapper();
		return (T) mapper.readValue(value, classes);
	}

	/**
	 * 将对象转成JSON字符串
	 * 
	 * @param t
	 * @return
	 * @throws JsonProcessingException
	 */
	public String toJson(T t) throws JsonProcessingException {
		ObjectMapper mapper = new ObjectMapper();
		return mapper.writeValueAsString(t);
	}

	@Override
	public String generateKey(String field) {
		return field;
	}

	@Override
	public String generateKey(String... fields) {
		if (fields == null || fields.length == 0) {
			return "";
		}
		StringBuilder builder = new StringBuilder();
		for (int i = 0; i < fields.length; ++i) {
			builder.append(i == 0 ? fields[i]
					: (BaseJedisProxy.KEY_SEPARATOR + fields[i]));
		}
		return builder.toString();
	}
}
